package com.dkd.flow.service.impl;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.common.enums.UpdateType;
import com.dkd.common.utils.DateUtils;
import com.dkd.common.utils.EbUtils;
import com.dkd.flow.domain.EProcessDefinition;
import com.dkd.flow.emums.IsDel;
import com.dkd.flow.emums.Status;
import com.dkd.flow.mapper.EProcessDefinitionMapper;
import com.dkd.flow.service.IEProcessDefinitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dkd.flow.mapper.EProcessGroupMapper;
import com.dkd.flow.domain.EProcessGroup;
import com.dkd.flow.service.IEProcessGroupService;
/**
 * 流程分组Service业务层处理
 *
 * @author itheima
 * @date 2025-01-26
 */
@Service
public class EProcessGroupServiceImpl extends ServiceImpl<EProcessGroupMapper, EProcessGroup> implements IEProcessGroupService {
    @Autowired
    private EProcessGroupMapper eProcessGroupMapper;
    @Autowired
    private IEProcessDefinitionService eProcessDefinitionService;
    /**
     * 查询流程分组
     *
     * @param ID 流程分组主键
     * @return 流程分组
     */
    @Override
    public EProcessGroup selectEProcessGroupByID(Long ID) {
        return eProcessGroupMapper.selectEProcessGroupByID(ID);
    }
    /**
     * 查询流程分组列表
     *
     * @param eProcessGroup 流程分组
     * @return 流程分组
     */
    @Override
    public List<EProcessGroup> selectEProcessGroupList(EProcessGroup eProcessGroup) {
        // 查询所有的 EProcessGroup 列表
        List<EProcessGroup> eProcessGroupList = eProcessGroupMapper.selectEProcessGroupList(eProcessGroup);
        if (eProcessGroupList.isEmpty()) {
            return eProcessGroupList;
        }
        // 收集所有 EProcessGroup 的 ID
        Set<Long> groupIds = eProcessGroupList.stream()
                .map(EProcessGroup::getID)
                .collect(Collectors.toSet());
        // 一次性查询出所有相关的 EProcessDefinition 记录
        QueryWrapper<EProcessDefinition> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("flow_group", groupIds)
                .isNotNull("flow_no")
                .eq("status", Status.OPEN.getValue()
                        .intValue())
                .eq("del_flag", IsDel.NOT_DEL.getValue())
                .select("ID", "FLOW_NO", "FLOW_TYPE", "FLOW_NAME", "FLOW_GROUP", "FLOW_IMG", "FLOW_REMARK", "AUTO_REPEAT", "MY_AUDIT_AUTO_PASS", "REMARK_REQUIRED", "NOT_VISIBLE_FOR_SPONSOR", "REMARK_TIP",
                        //"JSON",
                        "REVISE", "WITHDRAW", "MULTI_POSITION_ENABLE", "ORDER_NUM", "STATUS", "DEL_FLAG", "CREATE_BY", "CREATE_TIME", "UPDATE_BY", "UPDATE_TIME"
                        /*"VERSION_CREATE_TIME",
                        "ORIGINAL_VERSION_ID",
                        "VERSION_NUMBER"*/);
        List<EProcessDefinition> allApproves = eProcessDefinitionService.list(queryWrapper);
        // 按 EProcessGroup 的 ID 进行分组
        Map<Long, List<EProcessDefinition>> approvesMapByGroupId = allApproves.stream()
                .collect(Collectors.groupingBy(EProcessDefinition::getFlowGroup));
        // 对每个 EProcessGroup 对应的 approves 按 flow_name 分组，并取每组 update_time 最晚的记录
        for (Map.Entry<Long, List<EProcessDefinition>> entry : approvesMapByGroupId.entrySet()) {
            List<EProcessDefinition> approves = entry.getValue();
            List<EProcessDefinition> latestApproves = approves.stream()
                    .filter(approve -> approve.getUpdateTime() != null) // 过滤掉 update_time 为 null 的记录
                    .collect(Collectors.groupingBy(EProcessDefinition::getFlowName))
                    .values()
                    .stream()
                    .map(group -> group.stream()
                            .max(Comparator.comparing(EProcessDefinition::getUpdateTime))
                            .orElse(null))
                    .filter(Objects::nonNull)
                    .sorted(Comparator.comparing(EProcessDefinition::getUpdateTime)
                            .reversed())
                    .collect(Collectors.toList());
            approvesMapByGroupId.put(entry.getKey(), latestApproves);
        }
        // 将分组后的 EProcessDefinition 列表关联到对应的 EProcessGroup 对象上
        for (EProcessGroup group : eProcessGroupList) {
            Long groupId = group.getID();
            List<EProcessDefinition> approves = approvesMapByGroupId.getOrDefault(groupId, new ArrayList<>());
            group.setApproves(approves);
        }
        return eProcessGroupList;
    }
    /**
     * 新增流程分组
     *
     * @param eProcessGroup 流程分组
     * @return 结果
     */
    @Override
    public int insertEProcessGroup(EProcessGroup eProcessGroup) {
        EbUtils.updateTableFields(UpdateType.ADD_FIELD, eProcessGroup);
        Integer result = save(eProcessGroup) ? 1 : 0;
        return result;
    }
    /**
     * 修改流程分组
     *
     * @param eProcessGroup 流程分组
     * @return 结果
     */
    @Override
    public int updateEProcessGroup(EProcessGroup eProcessGroup) {
        eProcessGroup.setUpdateTime(DateUtils.getNowDate());
        return eProcessGroupMapper.updateEProcessGroup(eProcessGroup);
    }
    /**
     * 批量删除流程分组
     *
     * @param IDs 需要删除的流程分组主键
     * @return 结果
     */
    @Override
    public int deleteEProcessGroupByIDs(Long[] IDs) {
        return eProcessGroupMapper.deleteEProcessGroupByIDs(IDs);
    }
    /**
     * 删除流程分组信息
     *
     * @param ID 流程分组主键
     * @return 结果
     */
    @Override
    public int deleteEProcessGroupByID(Long ID) {
        return eProcessGroupMapper.deleteEProcessGroupByID(ID);
    }
}
